<template>

    <el-button @click="showAdd()" type="primary">+新增</el-button>
    <el-button @click="batchDel()" type="primary" :icon="Delete">删除</el-button>

    <div style="float: right;">
        <el-icon style="margin-right: 10px;" @click="loadPage()">
            <RefreshRight />
        </el-icon>
        <el-icon style="margin-right: 10px;">
            <Setting />
        </el-icon>
        <el-icon style="margin-right: 10px;" @click="changeIsFilter">
            <Filter />
        </el-icon>
    </div>

    <br>

    <div style="margin-top: 10px;" v-show="isFilter">
        商品名称:<el-input v-model="page.goodInfoName" style="width: 100px" placeholder="请输入商品名称" />
        生产批次:<el-input v-model="page.productionBatches" style="width: 150px" placeholder="请输入生产批次" />
        保质期(天):<el-input v-model="page.shelfLife" style="width: 100px" placeholder="请输入保质期" />
        生产许可证号:<el-input v-model="page.productionLicenseCode" style="width: 150px" placeholder="请输入生产许可证号" />
        生产企业:<el-input v-model="page.manufacturers" style="width: 100px" placeholder="请输入生产企业" />
        <el-button type="primary" @click="getTraceList()">查询</el-button>
    </div>

    <el-table :data="traceList" border style="width: 100%;margin-top: 20px;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column type="index" :index="indexMethod" label="序号" />
        <el-table-column prop="goodInfoName" label="商品名称" />
        <el-table-column prop="productionBatches" label="生产批次" />
        <el-table-column prop="shelfLife" label="保质期(天)" width="100" />
        <el-table-column prop="productionLicenseCode" label="生产许可证号" />
        <el-table-column prop="manufacturers" label="生产企业" />
        <el-table-column prop="address" label="信息完善度" />
        <el-table-column prop="createName" label="创建人" />
        <el-table-column prop="createTime" label="创建时间">
            <template v-slot="scope">
                <el-text v-if="scope.row.createTime == null ? '' : scope.row.createTime">{{
        scope.row.createTime.replace("T",
            " ").substring(0, 19) }}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="updateName" label="修改人" />
        <el-table-column prop="updateTime" label="修改时间">
            <template v-slot="scope">
                <el-text v-if="scope.row.updateTime == null ? '' : scope.row.updateTime">{{
        scope.row.updateTime.replace("T",
            " ").substring(0, 19) }}</el-text>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="214">
            <template v-slot="scope">
                <el-button size="small" link type="primary"
                    @click="jumpTraceInfo(scope.row.productionBatches,scope.row.traceabilityId)">详情</el-button>
                <el-button size="small" link type="primary" @click="showUpd(scope.row.productionBatches,scope.row.traceabilityId)">修改</el-button>
                <el-button size="small" link type="warning">导出溯源码</el-button>
                <el-button size="small" link type="danger" @click="delTrace(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <table>
        <tr>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[3, 5, 8]" :background="true" layout="total, slot, prev, pager, next" prev-text="上一页"
                    next-text="下一页" :total="page.totalCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <span>,每页{{ page.pageSize }}条,当前第{{ page.pageIndex }}/{{ page.totalPage }}页</span>
                    <el-button @click="handleCurrentChange(1)" :disabled="page.pageIndex == 1"
                        class="btn-prev">首页</el-button>
                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[3, 5, 8]" :background="true" layout="slot, sizes, jumper" prev-text="上一页"
                    next-text="下一页" :total="page.totalCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <el-button @click="handleCurrentChange(page.totalPage)" :disabled="page.pageIndex == page.totalPage"
                        class="btn-prev">尾页</el-button>
                </el-pagination>
            </td>
        </tr>
    </table>
    <!-- -----------------------------------------------------------添加对话框----------------------------------------------------------------------------- -->
    <el-dialog v-model="dialogFormVisible" title="基本信息" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
            <el-form-item label="商品名称" prop="goodInfoName">
                <el-select v-model="form.goodInfoName" placeholder="请选择商品" clearable>
                    <el-option v-for="item in goodList" :label="item.goodsInfoName" :value="item.goodsInfoName" />
                </el-select>
            </el-form-item>
            <el-form-item label="生产批次" prop="productionBatches">
                <el-input v-model="form.productionBatches" />
            </el-form-item>
            <el-form-item label="保质期(天)" prop="shelfLife">
                <el-input v-model.number="form.shelfLife" />
            </el-form-item>
            <el-form-item label="生产许可证号" prop="productionLicenseCode">
                <el-input v-model="form.productionLicenseCode" />
            </el-form-item>
            <el-form-item label="生产企业" prop="manufacturers">
                <el-input v-model="form.manufacturers" />
            </el-form-item>
            <el-form-item label="封面图" prop="coverImg">
                <el-upload class="avatar-uploader" action="http://localhost:24364/api/Traceability/UploadFiles"
                    :show-file-list="false" :on-success="handleAvatarSuccess">
                    <img v-if="form.coverImg" :src="form.coverImg" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" v-show="isShow == false" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button type="primary" v-show="isShow==true" @click="updTrace()">
                    修改
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Setting, RefreshRight, Filter } from '@element-plus/icons-vue'
import { Plus } from '@element-plus/icons-vue'
const route = useRoute();
const router = useRouter();
const form = reactive({
    traceabilityId: 0,
    goodInfoName: "",
    productionBatches: "",
    shelfLife: '',
    productionLicenseCode: "",
    manufacturers: "",
    coverImg: "",
    createName: localStorage.getItem("userName"),
    createTime: new Date(),
    updateName: localStorage.getItem("userName"),
    updateTime: new Date(),
})
const isShow = ref(false);
const isFilter = ref(false);
const dialogFormVisible = ref(false);

//跳转详情
const jumpTraceInfo = (productionBatches: any,traceabilityId:any) => {
    router.push({
        name: 'TraceabilityInfo',
        query: {
            productionBatches: productionBatches,
            traceabilityId:traceabilityId
        }
    })
}


//刷新页面
const loadPage = () => {
    location.reload();
}

//显示/隐藏查询条件
const changeIsFilter = () => {
    if (isFilter.value == false) {
        isFilter.value = true;
    }
    else {
        isFilter.value = false;
    }
}

//添加显示对话框
const showAdd = () => {
    //打开对话框
    dialogFormVisible.value = true;
    isShow.value = false;
    //显示商品名称
    showGood();
    // 截取年月日时分秒
    const now = new Date().toISOString().substring(0, 10).replaceAll("-", '');
    const now1 = new Date().toISOString().substring(11, 19).replaceAll(":", '');
    form.productionBatches = '' + now + now1;

}
//商品显示
const goodList = ref([])
const showGood = () => {
    axios.get("/api/Good/GetGoodInfo")
        .then(res => {
            goodList.value = res.data.data
        })
        .catch(err => {
            console.log(err);
        })
}

//表单校验
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    goodInfoName: [
        { required: true, message: '商品名称不能为空', trigger: 'blur' },
    ],
    productionBatches: [
        {
            required: true,
            message: '生产批次不能为空',
            trigger: 'blur',
        },
        { min: 0, max: 30, message: '最多输入30位字符', trigger: 'blur' },
    ],
    shelfLife: [
        {
            required: true,
            message: '保质期不能为空',
            trigger: 'blur',
        }, { min: 0, max: 5, message: '最多输入5位数字', trigger: 'blur' },
        { type: 'number', message: "只允许输入数字"}
    ],
    productionLicenseCode: [
        {
            required: true,
            message: '生产许可证号不能为空',
            trigger: 'blur',
        }, { min: 0, max: 30, message: '最多输入30位字符', trigger: 'blur' },
        // { pattern: /^[A-Za-z0-9]$/, message: "只能输入数字和字母", trigger: "blur" }
    ],
    manufacturers: [
        {
            required: true,
            message: '生产企业不能为空',
            trigger: 'blur',
        },
        { min: 0, max: 30, message: '最多输入30位字符', trigger: 'blur' },
        // { pattern: /^[\u4E00-\u9FA5A-Za-z]$ /, message: "允许输入任意字符（主要为中文、字母）", trigger: "blur" }
    ],
    coverImg: [
        {
            required: true,
            message: '封面图不能为空',
            trigger: 'blur',
        },
    ],
})

//添加
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post("/api/Traceability/Create", form)
                .then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success("添加成功");
                        dialogFormVisible.value = false;
                        router.push({
                            name: 'TraceabilityInfo',
                            // query:{

                            // }
                        })
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}
//打开修改对话框
const showUpd = (productionBatches:any,traceabilityId: any) => {
    //打开对话框
    dialogFormVisible.value = true;
    isShow.value = true;
    backfill(productionBatches,traceabilityId);
}

//返填
const backfill = (productionBatches:any,traceabilityId: any) => {
    axios.get("/api/Traceability/Backfill" ,{
        params:{
            ProductionBatches:productionBatches,
            TraceabilityId:traceabilityId
        }
    })
        .then(res => {
            form.traceabilityId = res.data.data.traceabilityId
            showGood();
            form.goodInfoName = res.data.data.goodInfoName
            form.productionBatches = res.data.data.productionBatches
            form.shelfLife = res.data.data.shelfLife
            form.productionLicenseCode = res.data.data.productionLicenseCode
            form.manufacturers = res.data.data.manufacturers
            form.coverImg = res.data.data.coverImg
            form.createName = res.data.data.createName
            form.createTime = res.data.data.createTime
        })
        .catch(err => {
            console.log(err);
        })
}

//修改
const updTrace = () => {
    axios.post("/api/Traceability/Update", form)
        .then(res => {
            if (res.data.code == 0) {
                ElMessage.success("修改成功");
                dialogFormVisible.value = false;
                router.push({
                    name: 'TraceabilityInfo',
                    // query:{

                    // }
                })
            }
        })
}

//图片
const handleAvatarSuccess = (url: string) => {
    form.coverImg = "http://localhost:24364" + url;
}




//序号
const indexMethod = (index: number) => {
    return index + 1;
}
//分页
const page = reactive({
    goodInfoName: '',
    productionBatches: '',
    shelfLife: '',
    productionLicenseCode: '',
    manufacturers: '',
    pageIndex: 1,
    pageSize: 5,
    totalCount: 0,
    totalPage: 0
})

//显示
const traceList = ref([])
const getTraceList = () => {
    axios.get("/api/Traceability/Show", {
        params: {
            GoodInfoName: page.goodInfoName,
            ProductionBatches: page.productionBatches,
            ShelfLife: page.shelfLife || 0,
            ProductionLicenseCode: page.productionLicenseCode,
            Manufacturers: page.manufacturers,
            PageIndex: page.pageIndex,
            PageSize: page.pageSize
        }
    })
        .then(res => {
            traceList.value = res.data.data.list
            page.totalCount = res.data.data.totalCount
            page.totalPage = res.data.data.totalPage
        })
        .catch(err => {
            console.log(err);
        })
}
//分页
const handleSizeChange = (val: number) => {
    page.pageSize = val;
    getTraceList();
}
const handleCurrentChange = (val: number) => {
    page.pageIndex = val;
    getTraceList();
}

//删除
const delTrace = (row: any) => {

    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("/api/Traceability/Delete", row)
                .then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success("删除成功");
                        getTraceList();
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作',
            })
        })

}
//多选框选中
const multipleSelection = ref([]);
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
    // console.log(val);
}

//批量删除
const batchDel = () => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("/api/Traceability/BatchDelete2", multipleSelection.value)
                .then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success("删除成功");
                        getTraceList();
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作',
            })
        })
}

//钩子
onMounted(() => {
    getTraceList();
})
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>